package service

import (
	"errors"
	"fmt"
	"iot-bridge/iot_cmd_up/distribute/conf"
	"iot-bridge/iot_cmd_up/distribute/dao/mysql"
	"iot-bridge/iot_cmd_up/distribute/dao/redis"
	"math"
	"strconv"
	"strings"

	log "common/log4go.v1"
)

var (
	ReportDataDao *mysql.ReportDataDao
	WeekTable     map[string]string
)

const (
	tableKey = "iot_mqtt_data_"
	TokenKey = "iot|token|cid|%s" //key全部改成 | 连接
)

func Init() error {
	var err error
	WeekTable = make(map[string]string, 0)
	for _, v := range conf.Conf.Table.ProductId {
		key := strings.Split(v, "|")
		WeekTable[key[1]] = key[0]
	}
	ReportDataDao, err = mysql.NewReportDataDao()
	if err != nil {
		log.Error("mysql.NewReportDataDao() error(%v)", err)
		return err
	}
	return nil
}

func Close() {

}

func MakeTable(productId string) (table string) {
	table = tableKey + WeekTable[productId]
	return
}

func VerifyToken(cid string, token string) error {
	cidTokenKey := fmt.Sprintf(TokenKey, cid)
	cidToken, err := redis.RedisGet(cidTokenKey)
	if err != nil {
		log.Error("%v", err)
		return err
	}
	if token != cidToken {
		log.Error("cid(%s) cidToken(%s) token(%s)", cid, cidToken, token)
		return errors.New("token校验错误")
	}
	return nil
}

//	func packetLen(packet []byte) (uint, uint) {
//		len := uint(0)
//		count := uint(0)
//		for _, v := range packet {
//			count++
//			len = len << 7
//			len = len | uint(v&^(1<<7))
//			if v&(1<<7) == 0 {
//				break
//			}
//		}
//		return len, count
//	}
func packetLen(packet []byte) (uint, uint) {
	flag128 := 128 // 1000 0000
	value := 0
	var shortIdLenData []byte
	var multiplier = 1
	index := 0
	for index < len(packet) {
		item := packet[index]
		shortIdLenData = append(shortIdLenData, item)
		index = index + 1
		if item&byte(flag128) == 0 {
			break
		}
	}
	for _, v := range shortIdLenData {
		digit := int(v)
		value = value + (digit&127)*multiplier
		multiplier = multiplier << 7
		if (digit & 128) != 0 {
			continue
		}
	}
	return uint(value), uint(index)
}

// Hexadecimal to decimal
func HexDec(h string) (n int64) {
	s := strings.Split(strings.ToUpper(h), "")
	l := len(s)
	i := 0
	d := float64(0)
	hex := map[string]string{"A": "10", "B": "11", "C": "12", "D": "13", "E": "14", "F": "15"}
	for i = 0; i < l; i++ {
		c := s[i]
		if v, ok := hex[c]; ok {
			c = v
		}
		f, err := strconv.ParseFloat(c, 10)
		if err != nil {
			log.Error("Hexadecimal to decimal error:", err.Error())
			return -1
		}
		d += f * math.Pow(16, float64(l-i-1))
	}
	return int64(d)
}
